package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IHotArticleService;
import com.heima.behavior.dto.ArticleStreamMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2022-07-10 12:03
 */
@Service
public class HotArticleServiceImpl implements IHotArticleService {

    @Autowired
    private IApArticleService apArticleService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 查询文章表中最近五天文章列表；循环遍历文章列表计算文章分值；将热点文章存入Redis实现排行榜
     */
    @Override
    public void compute() {
        //1.查询文章表中最近五天文章列表
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        //1.1 设置未下架 未删除条件
        queryWrapper.eq(ApArticle::getIsDown, false);
        queryWrapper.eq(ApArticle::getIsDelete, false);
        //1.2 设置查询时间区间
        Date from = getFromAndToDate(-30);
        Date to = getFromAndToDate(0);
        queryWrapper.between(ApArticle::getPublishTime, from, to);
        List<ApArticle> list = apArticleService.list(queryWrapper);

        //2.循环遍历文章列表计算文章分值
        if (!CollectionUtils.isEmpty(list)) {
            for (ApArticle article : list) {
                //2.1 计算每篇文章得分
                int score = computeScore(article);
                //TODO 具体大于分值多少才认得为热点 产品经理来定
                if (score > 0) {
                    //3.将热点文章存入Redis实现排行榜
                    String redisKeyPrefix = "leadnews:article:hot:page:";
                    //3.1 将所有文章存入到Redis首页排行榜
                    String indexKey = redisKeyPrefix + "0";
                    //3.2 获取文章JSON数据
                    ApArticle cache = new ApArticle();
                    cache.setId(article.getId());
                    cache.setTitle(article.getTitle());
                    cache.setImages(article.getImages());
                    cache.setAuthorId(article.getAuthorId());
                    cache.setAuthorName(article.getAuthorName());
                    cache.setLayout(article.getLayout());
                    cache.setStaticUrl(article.getStaticUrl());
                    String articleJson = JSON.toJSONString(cache);
                    redisTemplate.opsForZSet().add(indexKey, articleJson, score);


                    //3.2 将文章存入当前频道排行榜
                    String channelKey = redisKeyPrefix + article.getChannelId();
                    redisTemplate.opsForZSet().add(channelKey, articleJson, score);

                    //3.3 设置缓存排行榜有效期 为1天
                    redisTemplate.expire(indexKey, 1, TimeUnit.DAYS);
                    redisTemplate.expire(channelKey, 1, TimeUnit.DAYS);
                }
            }
        }
    }


    /**
     * 为入参的文章计算分值
     *
     * @param article
     * @return
     */
    private int computeScore(ApArticle article) {
        int score = 0;
        // 阅读 +1  点赞 +3  评论 +5  收藏 +8
        if (article.getViews() != null) {
            score += article.getViews() * 1;
        }
        if (article.getLikes() != null) {
            score += article.getLikes() * 3;
        }
        if (article.getComment() != null) {
            score += article.getComment() * 5;
        }
        if (article.getCollection() != null) {
            score += article.getCollection() * 8;
        }
        return score;
    }


    /**
     * 获取指定天数日期 正数：未来时间  负数：以前时间
     *
     * @param datecount
     * @return
     */
    public static Date getFromAndToDate(Integer datecount) {
        //创建日期对象
        Calendar calendar = Calendar.getInstance();
        //设置日期
        calendar.add(Calendar.DATE, datecount);
        //设置时分秒
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }


    /**
     * 根据实时计算文章增量分值，更新redis缓存 热点文章排行旁 ；数据库中 文章表
     *
     * @param articleStreamMessage
     */
    @Override
    public void updateCacheAndDB(ArticleStreamMessage articleStreamMessage) {
        //1.根据文章ID查询文章对象
        ApArticle article = apArticleService.getById(articleStreamMessage.getArticleId());

        //2.构建Redis缓存文章对象-TODO 一定要跟以前的缓存对象一致
        ApArticle cache = new ApArticle();
        cache.setId(article.getId());
        cache.setTitle(article.getTitle());
        cache.setImages(article.getImages());
        cache.setAuthorId(article.getAuthorId());
        cache.setAuthorName(article.getAuthorName());
        cache.setLayout(article.getLayout());
        cache.setStaticUrl(article.getStaticUrl());
        String articleJson = JSON.toJSONString(cache);

        //3.更新redis缓存中文章排行榜  首页  某个频道
        String keyPrefix = "leadnews:article:hot:page:";
        String indexKey = keyPrefix + "0";
        String channelKey = keyPrefix + article.getChannelId();

        //3.1 计算该文章增量得分（根据聚合行为结果）
        Long scorePlus = computeScore(articleStreamMessage);

        //3.2 判断Redis中元素是否存在
        Double score = redisTemplate.opsForZSet().score(indexKey, articleJson);
        if (score != null) {
            //3.2.1 如果redis存在，直接对得分进行增加
            redisTemplate.opsForZSet().incrementScore(indexKey, articleJson, scorePlus);
            redisTemplate.opsForZSet().incrementScore(channelKey, articleJson, scorePlus);

        } else {
            //3.2.2 如果Redis不存在，计算历史得分+增量得分，将数据缓存到Redis
            int historyScore = computeScore(article);
            redisTemplate.opsForZSet().add(indexKey, articleJson, historyScore + scorePlus);
            redisTemplate.opsForZSet().add(channelKey, articleJson, historyScore + scorePlus);
        }

        //4.更新数据库文章表操作行为值
        LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticle::getId, article.getId());
        updateWrapper.setSql("views = views +" + articleStreamMessage.getView());
        updateWrapper.setSql("likes = likes +" + articleStreamMessage.getLike());
        updateWrapper.setSql("comment = comment +" + articleStreamMessage.getComment());
        updateWrapper.setSql("collection = collection +" + articleStreamMessage.getCollect());
        apArticleService.update(updateWrapper);
    }


    /**
     * 计算当日的增量分数  当日的操作整体权重*3
     *
     * @param message
     * @return
     */
    private Long computeScore(ArticleStreamMessage message) {
        Long score = 0L;
        score += message.getView() * 1 * 3;
        score += message.getLike() * 3 * 3;
        score += message.getComment() * 5 * 3;
        score += message.getCollect() * 8 * 3;
        return score;
    }

}
